package util;

import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.Connection;


public class DbUtil {
    public Connection conn=null;//数据库连接对象
    public Statement stmt=null;//执行sql语句的对象
    public ResultSet rs=null;//存放查询结果的对象

    public void getConnection() {

        try {
            //1.注册驱动
            Class.forName("com.mysql.cj.jdbc.Driver");

            //2.创建数据库连接
            String url="jdbc:mysql://localhost:3306/onlineshop?useSSL=false&characterEncoding=utf-8&serverTimezone=GMT%2B8";
            conn=DriverManager.getConnection(url,"root","123456");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            System.out.println("连接数据库失败");
            e.printStackTrace();
        }
    }

    public ResultSet executeQuery(String sql) {
        try {
            if (conn==null) {
                getConnection();
            }
            if (stmt==null) {
                stmt=conn.createStatement();
            }
            return stmt.executeQuery(sql);

        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
            System.out.println("执行查询异常");
            return null;
        }

    }

    public int executeUpdate(String sql) {
        try {
            if (conn==null) {
                getConnection();
            }
            if (stmt==null) {
                stmt=conn.createStatement();
            }
            return stmt.executeUpdate(sql);

        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
            System.out.println("执行更新异常");
            return -1;

        }

    }


    public void close() {
        try {
            if(rs!=null) {
                rs.close();
            }
            if(stmt!=null) {
                stmt.close();
            }
            if(conn!=null) {
                conn.close();
            }

        } catch (Exception e) {
            // TODO: handle exception
        }
    }


}
